package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private MongoTemplate template;
    @Autowired
    private TravelRepository travelRepository;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;



    @Override
    public Travel get(String id) {
        return travelRepository.findById(id).get();
    }

    @Override
    public List<Travel> selectAll() {
        return travelRepository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {
        //创建Query对象,根据过滤条件查询总条数,此处没有限制条件,所以用空的查询对象查
        Query query = new Query();
        //添加限制,如果有目的地
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //添加限制,如果有花费限制
        if (qo.getPerExpendType()!=null){
            query.addCriteria(Criteria.where("perExpend")
                    .gte(qo.getPerExpendType().getMin())
                    .lte(qo.getPerExpendType().getMax())
            );
        }
        //添加限制,如果有出行天数
        if (qo.getDayType()!=null){
            query.addCriteria(Criteria.where("day")
                    .gte(qo.getDayType().getMin())
                    .lte(qo.getDayType().getMax())
            );
        }

        //创建过滤查询
        //有数据,进行分页操作,创建新的分页对象,此索引从0开始,所以要减一,分页的字段与数据库一致
        //如果有分类类别
        Pageable pageAble;
        if (qo.getOrderType()==1){      //1按照时间
            pageAble = PageRequest.of(qo.getCurrentPage() - 1,
                    qo.getPageSize(), Sort.Direction.DESC, "travelTime");
        }else if (qo.getOrderType()==2){    //2按照热度
            pageAble = PageRequest.of(qo.getCurrentPage() - 1,
                    qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        }else {                             //兜底
            pageAble = PageRequest.of(qo.getCurrentPage() - 1,
                    qo.getPageSize(), Sort.Direction.ASC, "_id");
        }

        //返回给控制器
        Page<Travel> page = DBHelper.query(template, Travel.class, query, pageAble);
        for (Travel travel : page.getContent()) {
               UserInfo userInfo = userInfoService.get(travel.getUserId());
               travel.setAuthor(userInfo);
        }
        return page;
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        travelRepository.save(travel);
    }

    @Override
    public void deleteById(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public void changeState(String id, Integer state) {
        //首先查出游记数据判断是否处于要审核的状态
        Travel travel = travelRepository.findById(id).get();
        if (travel==null||travel.getState()!=Travel.STATE_WAITING){
            throw new LogicException("参数错误,没有此游记或游记不处于待发布状态");
        }
        //将游记状态改为管理员改变的状态
        if (state==Travel.STATE_RELEASE){
            //改为审核通过状态,除了改变审核状态外,还要更改发布时间,最后更新的事件,记录操作员信息等
            travel.setState(state);
            travel.setLastUpdateTime(new Date());
            travel.setReleaseTime(new Date());
        }else if (state==Travel.STATE_REJECT){
            //改为审核拒绝状态
            travel.setState(state);
            //发布时间为null
            travel.setReleaseTime(null);
            //最后更新时间
            travel.setLastUpdateTime(new Date());
            //记录操作员
        }else {
            //状态输入错误
            throw new LogicException("审核状态错误");
        }
        //更改
        this.update(travel);
    }

    @Override
    public String getContentById(String id) {
        //查询游记
        Travel travel = travelRepository.findById(id).orElse(null);
        //返回结果
        return travel.getContent();
    }

    @Override
    public List<Travel> viewnumTop3(String destId) {
        //查询点击量前三的游记文章
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC,"viewnum");
        return travelRepository.findByDestId(destId, pageable);
    }

    @Override
    public void saveOrUpdate(Travel travel, UserInfo userInfo) {
        //保存游记
        /*
        * 浏览器给的数据
        * id:
state: 1
title: 可接收马萨卡
coverUrl: https://liu12424.oss-cn-shenzhen.aliyuncs.com/9055daf7-b421-4c40-b77f-d0098b2dc0e8.png
travelTime: 2020-07-19
person: 3
isPublic: 1
day: 55
perExpend: 8521
destId: 5e2ab4f48847000059006e1d
summary: 上课就能卡萨
content: 11
        * */
        //还缺少数据     destName=目的地名字      作者id
        //createTime文章的创建时间
        //给对象添加目的地名
        Destination dest = destinationService.get(travel.getDestId());
        travel.setDestName(dest.getName());
        //给对象添加作者的id
        travel.setUserId(userInfo.getId());
        //最后更新时间
        travel.setLastUpdateTime(new Date());
        //如果有id则为更新,没有则为保存
        if (StringUtils.hasLength(travel.getId())){
            travelRepository.save(travel);
        }else {
            travel.setId(null);
            //文章的创建时间
            travel.setCreateTime(new Date());
            travelRepository.save(travel);
        }
    }

    @Override
    public List<Travel> queryByDestName(String keyword) {
        List<Travel> byDestName = travelRepository.findByDestName(keyword);
        for (Travel travel : byDestName) {
            //查作者
            UserInfo user = userInfoService.get(travel.getUserId());
            travel.setAuthor(user);
        }
        return byDestName;
    }
}
